package com.yzc.android.ui.base.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.OnClick;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapLoadedCallback;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.MyLocationData.Builder;
import com.yzc.android.KDApp;
import com.yzc.android.R;
import com.yzc.android.beans.BeaconBean;
import com.yzc.android.event.BDLocationResponseEvent;
import com.yzc.android.event.BeaconScanEvent;
import com.yzc.android.event.EventBusManager;
import com.yzc.android.event.EventLifeCycleHandler;
import com.yzc.android.manager.location.BaiduLocationManager;
import com.yzc.android.manager.sensor.ESSensorManager;
import com.yzc.android.manager.sensor.SensorConstant;
import com.yzc.android.manager.sensor.config.pull.PullSensorConfig;
import com.yzc.android.manager.sensor.sensors.SensorUtils;
import com.yzc.android.ui.SensorsThread;
import com.yzc.android.utils.FileUtils;
import com.yzc.android.utils.LogUtils;
import com.yzc.android.utils.ToastUtil;
import org.json.JSONObject;

/**
 * Created by yzc on 16/5/21.
 */
public class DemoMapViewFragment extends NavBarBaseFragment implements OnMapLoadedCallback, OnClickListener {
    @Bind(R.id.map_sensor)
    MapView mMapSensor;

    @Bind(R.id.tv_acceleration_des)
    TextView mTvAccelerationDes;

    @Bind(R.id.tv_yaw_des)
    TextView mTvYawDes;

    @Bind(R.id.tv_ibeacon_region_alert)
    TextView mTvIbeaconRegionAlert;

    @Bind(R.id.btn_start_sense)
    Button mBtnStartSense;

    @Bind(R.id.btn_end_sense)
    Button mBtnEndSense;

    @Bind(R.id.btn_sharp_quick)
    Button mBtnSharpQuick;

    @Bind(R.id.btn_sharp_slow)
    Button mBtnSharpSlow;

    @Bind(R.id.btn_sharp_turn)
    Button mBtnSharpTurn;

    @Bind(R.id.btn_delete_log)
    Button mBtnDeleteLog;

    private BaiduMap mBaiduMap;

    private BitmapDescriptor mCurrentMarker;

    private EventLifeCycleHandler mEventHandler;

    // 业务相关
    private ESSensorManager mSensorManager;

    private SensorsThread mAccelerometerSensorThread;

    private SensorsThread mGyroscopeSensorThread;

    private SensorsThread mMagneticFieldThread;

    private SensorsThread mProximityThread;

    //private SensorsThread mStepCounterThread;

    private SensorsThread mPassiveLocationThread;

    private boolean mIsSensing = false;

    private DriveTraceOverlay mTraceOverlay;

    @Override
    public int getLayout() {
        return R.layout.layout_activity_sensor;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        setHeaderTitle("驾驶行为测试");
        mNavigationBar.setRightOnClickListener(this);
        mNavigationBar.showRightView(false);

        mBaiduMap = mMapSensor.getMap();
        mBaiduMap.setMyLocationEnabled(true);
        mBaiduMap.setOnMapLoadedCallback(this);
        mCurrentMarker = BitmapDescriptorFactory.fromResource(R.mipmap.mylocation);
        MyLocationConfiguration config = new MyLocationConfiguration(LocationMode.FOLLOWING, true, mCurrentMarker);
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomTo(16));
        mBaiduMap.setMyLocationConfigeration(config);

        mTraceOverlay = new DriveTraceOverlay(mBaiduMap);

        initSensors();

        mEventHandler = new EventLifeCycleHandler() {
            public void onEvent(final BDLocationResponseEvent event) {
                BDLocation bdLocation = event.getData();
                if (bdLocation != null) {
                    try {
                        if (mIsSensing) {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.putOpt("radius", bdLocation.getRadius());
                            jsonObject.putOpt("latitude", bdLocation.getLatitude());
                            jsonObject.putOpt("longitude", bdLocation.getLongitude());
                            jsonObject.putOpt("direction", bdLocation.getDirection());
                            if (bdLocation.hasSpeed()) {
                                jsonObject.putOpt("speed", bdLocation.getSpeed());
                            }

                            if (bdLocation.hasAltitude()) {
                                jsonObject.putOpt("altitude", bdLocation.getAltitude());
                            }
                            LogUtils.local(SensorConstant.kGPSLogTag, jsonObject.toString() + "\n\n");
                            mTraceOverlay.addPoint(bdLocation);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    MyLocationData locData = new Builder().accuracy(bdLocation.getRadius())
                            .direction(bdLocation.getDirection())
                            .latitude(bdLocation.getLatitude())
                            .longitude(bdLocation.getLongitude())
                            .build();
                    mBaiduMap.setMyLocationData(locData);
                }
            }

            public void onEvent(final BeaconScanEvent event) {
                BeaconBean beaconBean = event.getData();
                if (beaconBean != null) {
                    mTvIbeaconRegionAlert.setText("您当前处于热点区域内");
                    mNavigationBar.showRightView(true);
                } else {
                    mTvIbeaconRegionAlert.setText("您离开了热点区域");
                    mNavigationBar.showRightView(false);
                }
            }
        };

        if (KDApp.getInstance().getBeacon() != null) {
            mTvIbeaconRegionAlert.setText("您当前处于热点区域内");
            mNavigationBar.showRightView(true);
        } else {
            mTvIbeaconRegionAlert.setText("您离开了热点区域");
            mNavigationBar.showRightView(false);
        }

        return view;
    }

    @Override
    public void onDestroyView() {
        LogUtils.d("Test", "onDestroyView");
        if (mMapSensor != null) {
            mMapSensor.onDestroy();
        }

        super.onDestroyView();
        if (mAccelerometerSensorThread != null) {
            mAccelerometerSensorThread.stopSensing();
        }

        if (mGyroscopeSensorThread != null) {
            mGyroscopeSensorThread.stopSensing();
        }

        if (mMagneticFieldThread != null) {
            mMagneticFieldThread.stopSensing();
        }

        if (mProximityThread != null) {
            mProximityThread.stopSensing();
        }

        //if (mStepCounterThread != null) {
        //    mStepCounterThread.stopSensing();
        //}

        if (mPassiveLocationThread != null) {
            mPassiveLocationThread.stopSensing();
        }
    }

    // onResume
    @Override
    public void onBack() {
        super.onBack();
        mMapSensor.onResume();
        EventBusManager.bindContainerAndHandler(this, mEventHandler).tryToRegisterIfNot();
        mTvAccelerationDes.setText(String.format("急加（减）速判断阈值：%s", SensorConstant.kAccelerationThreshold));
        mTvYawDes.setText(String.format("急转弯判断阈值：%s", SensorConstant.kYawThreshold));
    }

    @Override
    public void onLeave() {
        super.onLeave();
        if (mMapSensor != null) {
            mMapSensor.onPause();
        }
    }

    @Override
    protected boolean enablePullRefresh() {
        return false;
    }

    @Override
    protected boolean enableDefaultBack() {
        return false;
    }

    @Override
    public void pullToRefreshHandler() {

    }

    @Override
    public void onClick(View v) {
        getContext().pushFragmentToBackStack(SensorSettingFragment.class, KDApp.getInstance().getBeacon());
    }

    @Override
    public void onMapLoaded() {
        BaiduLocationManager.getInstance().startLocation();
    }

    @OnClick(R.id.btn_start_sense)
    public void onStartSense(Button button) {
        ToastUtil.getInstance().showToast("开始记录");
        mIsSensing = true;
        button.setEnabled(false);
        mBtnEndSense.setEnabled(true);
        mBtnDeleteLog.setEnabled(false);
        mTraceOverlay.clearPoint();

        if (mAccelerometerSensorThread != null) {
            mAccelerometerSensorThread.startSensing();
        }

        if (mGyroscopeSensorThread != null) {
            mGyroscopeSensorThread.startSensing();
        }

        if (mMagneticFieldThread != null) {
            mMagneticFieldThread.startSensing();
        }

        if (mProximityThread != null) {
            mProximityThread.startSensing();
        }

        //if (mStepCounterThread != null) {
        //    mStepCounterThread.startSensing();
        //}

        if (mPassiveLocationThread != null) {
            mPassiveLocationThread.startSensing();
        }
    }

    @OnClick(R.id.btn_end_sense)
    public void onEndSense(Button button) {
        ToastUtil.getInstance().showToast("停止记录");
        mIsSensing = false;
        button.setEnabled(false);
        mBtnStartSense.setEnabled(true);
        mBtnDeleteLog.setEnabled(true);
        if (mAccelerometerSensorThread != null) {
            mAccelerometerSensorThread.stopSensing();
        }

        if (mGyroscopeSensorThread != null) {
            mGyroscopeSensorThread.stopSensing();
        }

        if (mMagneticFieldThread != null) {
            mMagneticFieldThread.stopSensing();
        }

        if (mProximityThread != null) {
            mProximityThread.stopSensing();
        }

        //if (mStepCounterThread != null) {
        //    mStepCounterThread.stopSensing();
        //}

        if (mPassiveLocationThread != null) {
            mPassiveLocationThread.stopSensing();
        }

        //FileUtils.zipFileAtPath(LogUtils.LOCAL_DEBUG_LOG_FOLDER+LogUtils.generateFileName(SensorConstant
        // .kAccelerometerLogTag),
        //                        LogUtils.LOCAL_DEBUG_LOG_FOLDER+LogUtils.generateFileZipName(SensorConstant
        // .kAccelerometerLogTag));
        //
        //FileUtils.zipFileAtPath(LogUtils.LOCAL_DEBUG_LOG_FOLDER+LogUtils.generateFileName(SensorConstant
        // .kGyroscopeLogTag),
        //                        LogUtils.LOCAL_DEBUG_LOG_FOLDER+LogUtils.generateFileZipName(SensorConstant
        // .kGyroscopeLogTag));
        //
        //FileUtils.zipFileAtPath(LogUtils.LOCAL_DEBUG_LOG_FOLDER+LogUtils.generateFileName(SensorConstant
        // .kMagneticFieldLogTag),
        //                        LogUtils.LOCAL_DEBUG_LOG_FOLDER+LogUtils.generateFileZipName(SensorConstant
        // .kMagneticFieldLogTag));
        //
        //FileUtils.zipFileAtPath(LogUtils.LOCAL_DEBUG_LOG_FOLDER+LogUtils.generateFileName(SensorConstant
        // .kProximityLogTag),
        //                        LogUtils.LOCAL_DEBUG_LOG_FOLDER+LogUtils.generateFileZipName(SensorConstant
        // .kProximityLogTag));
        //
        //FileUtils.zipFileAtPath(LogUtils.LOCAL_DEBUG_LOG_FOLDER+LogUtils.generateFileName(SensorConstant
        // .kStepCounterLogTag),
        //                        LogUtils.LOCAL_DEBUG_LOG_FOLDER+LogUtils.generateFileZipName(SensorConstant
        // .kStepCounterLogTag));

        //FileUtils.zipFileAtPath(LogUtils.LOCAL_DEBUG_LOG_FOLDER+LogUtils.generateFileName(SensorConstant
        // .kPassiveLocationLogTag),
        //                        LogUtils.LOCAL_DEBUG_LOG_FOLDER+LogUtils.generateFileZipName(SensorConstant
        // .kPassiveLocationLogTag));

        //FileUtils.zipFileAtPath(LogUtils.LOCAL_DEBUG_LOG_FOLDER+LogUtils.generateFileName(SensorConstant.kGPSLogTag),
        //                        LogUtils.LOCAL_DEBUG_LOG_FOLDER+LogUtils.generateFileZipName(SensorConstant
        // .kGPSLogTag));
        //ToastUtil.getInstance().showToast("压缩记录完成");
    }

    @OnClick(R.id.btn_delete_log)
    public void onDeleteLogButton() {
        ToastUtil.getInstance().showToast("删除日志");
        FileUtils.deleteFile(LogUtils.LOCAL_DEBUG_LOG_FOLDER);
        mTraceOverlay.clearPoint();
        mTraceOverlay.removeFromMap();
    }

    @OnClick(R.id.btn_sharp_quick)
    public void onSharpQuickButton() {
        ToastUtil.getInstance().showToast("急加速+1");
        LogUtils.local(SensorConstant.kDriveMannerLogTag, "急加速");

    }

    @OnClick(R.id.btn_sharp_slow)
    public void onSharpSlowButton() {
        ToastUtil.getInstance().showToast("急减速+1");
        LogUtils.local(SensorConstant.kDriveMannerLogTag, "急减速");

    }

    @OnClick(R.id.btn_sharp_turn)
    public void onSharpTurnButton() {
        ToastUtil.getInstance().showToast("急转弯+1");
        LogUtils.local(SensorConstant.kDriveMannerLogTag, "急转弯");

    }

    private void initSensors() {
        try {
            if (mSensorManager == null) {
                mSensorManager = ESSensorManager.getSensorManager(getContext());
                mSensorManager.setSensorConfig(SensorUtils.SENSOR_TYPE_ACCELEROMETER,
                                               PullSensorConfig.POST_SENSE_SLEEP_LENGTH_MILLIS, 1000L);
                mSensorManager.setSensorConfig(SensorUtils.SENSOR_TYPE_ACCELEROMETER,
                                               PullSensorConfig.SENSE_WINDOW_LENGTH_MILLIS, 1000L);
                mSensorManager.setSensorConfig(SensorUtils.SENSOR_TYPE_GYROSCOPE,
                                               PullSensorConfig.POST_SENSE_SLEEP_LENGTH_MILLIS, 1000L);
                mSensorManager.setSensorConfig(SensorUtils.SENSOR_TYPE_GYROSCOPE,
                                               PullSensorConfig.SENSE_WINDOW_LENGTH_MILLIS, 1000L);

                mSensorManager.setSensorConfig(SensorUtils.SENSOR_TYPE_MAGNETIC_FIELD,
                                               PullSensorConfig.POST_SENSE_SLEEP_LENGTH_MILLIS, 1000L);
                mSensorManager.setSensorConfig(SensorUtils.SENSOR_TYPE_MAGNETIC_FIELD,
                                               PullSensorConfig.SENSE_WINDOW_LENGTH_MILLIS, 1000L);

                //mSensorManager.setSensorConfig(SensorUtils.SENSOR_TYPE_PROXIMITY,
                //                               PullSensorConfig.POST_SENSE_SLEEP_LENGTH_MILLIS, 1000L);
                //mSensorManager.setSensorConfig(SensorUtils.SENSOR_TYPE_PROXIMITY,
                //                               PullSensorConfig.SENSE_WINDOW_LENGTH_MILLIS, 1000L);

                //mSensorManager.setSensorConfig(SensorUtils.SENSOR_TYPE_STEP_COUNTER,
                //                               PullSensorConfig.POST_SENSE_SLEEP_LENGTH_MILLIS, 1000L);
                //mSensorManager.setSensorConfig(SensorUtils.SENSOR_TYPE_STEP_COUNTER,
                //                               PullSensorConfig.SENSE_WINDOW_LENGTH_MILLIS, 1000L);

                //mSensorManager.setSensorConfig(SensorUtils.SENSOR_TYPE_PASSIVE_LOCATION,
                //                               PullSensorConfig.POST_SENSE_SLEEP_LENGTH_MILLIS, 1000L);
                //mSensorManager.setSensorConfig(SensorUtils.SENSOR_TYPE_PASSIVE_LOCATION,
                //                               PullSensorConfig.SENSE_WINDOW_LENGTH_MILLIS, 1000L);
            }

            if (mAccelerometerSensorThread == null) {
                mAccelerometerSensorThread = new SensorsThread(getContext(), mSensorManager,
                                                               SensorUtils.SENSOR_TYPE_ACCELEROMETER);
            }

            if (mGyroscopeSensorThread == null) {
                mGyroscopeSensorThread = new SensorsThread(getContext(), mSensorManager,
                                                           SensorUtils.SENSOR_TYPE_GYROSCOPE);
            }

            if (mMagneticFieldThread == null) {
                mMagneticFieldThread = new SensorsThread(getContext(), mSensorManager,
                                                         SensorUtils.SENSOR_TYPE_MAGNETIC_FIELD);
            }

            if (mProximityThread == null) {
                mProximityThread = new SensorsThread(getContext(), mSensorManager, SensorUtils.SENSOR_TYPE_PROXIMITY);
            }

            //if (mStepCounterThread == null) {
            //    mStepCounterThread = new SensorsThread(getContext(), mSensorManager,
            //                                           SensorUtils.SENSOR_TYPE_STEP_COUNTER);
            //}

            if (mPassiveLocationThread == null) {
                mPassiveLocationThread = new SensorsThread(getContext(), mSensorManager,
                                                           SensorUtils.SENSOR_TYPE_PASSIVE_LOCATION);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
